package lc.oa.ui.login;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import lc.oa.App;
import lc.oa.BuildConfig;
import lc.oa.data.LoginRepository;
import lc.oa.data.model.LoggedInUser;
import lc.oa.R;
import lc.oa.enums.HttpStatus;
import lombok.SneakyThrows;

/*
MVVM(Model-ViewModel-View-Controller) 模式 Model
Activity交互层
View(Activity) <--> ViewModel <---> Controller
* */
public class LoginViewModel extends ViewModel {

    private MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>();
    private MutableLiveData<LoginResult> loginResult = new MutableLiveData<>();
    private LoginRepository loginRepository;

    LoginViewModel(LoginRepository loginRepository) {
        this.loginRepository = loginRepository;
    }

    LiveData<LoginFormState> getLoginFormState() {
        return loginFormState;
    }

    LiveData<LoginResult> getLoginResult() {
        return loginResult;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 200:
                    // Users users=(Users)msg.obj;
                    LoggedInUser loggedInUser = (LoggedInUser) msg.obj;
                    loggedInUser.setDisplayName(loggedInUser.getUserName());
                    // Result<LoggedInUser> result= new Result.Success<>(loggedInUser);
                    loginResult.setValue(new LoginResult(new LoggedInUserView(loggedInUser.getDisplayName())));
                    break;
                case -1:
                    loginResult.setValue(new LoginResult(R.string.login_failed, msg.obj.toString()));
                    break;
            }
        }
    };

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 登录验证
     *
     * @param username
     * @param password
     */
    public void login(String username, String password, Context context) {
        // can be launched in a separate asynchronous job
        // Result<LoggedInUser> result = loginRepository.login(username, password);

        //通过 LiveData机制通知监听事件
        //loginViewModel.getLoginResult().observe
//        if (result instanceof Result.Success) {
//            LoggedInUser data = ((Result.Success<LoggedInUser>) result).getData();
//            loginResult.setValue(new LoginResult(new LoggedInUserView(data.getDisplayName())));
//        } else {
//            loginResult.setValue(new LoginResult(R.string.login_failed));
//        }

        //同步Post请求必须在子线程中执行
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                loginHandler(context, username, password);
            }
        }).start();

    }

    final String url = BuildConfig.AUTH_API_URL + "/api/v1/Login/Login";

    private void loginHandler(Context context, String username, String password) throws JSONException {
        try {
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            RequestFuture<JSONObject> future = RequestFuture.newFuture();
            // SignData signData = new SignData();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("loginType", "10");
            jsonObject.put("signData", "");
            jsonObject.put("signVal", "");
            jsonObject.put("userName", username);
            jsonObject.put("userPassword", md5(password)); //"82273a6ba2126d3af24ce2d0cb0af515");
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, future, future);
            requestQueue.add(request);
            JSONObject response = null;

            response = future.get(); // this will block
            if (Integer.parseInt(response.get("code") + "") == HttpStatus.OK.getCode().intValue()) {
                Log.d("登录信息", "登录成功!-->" + response);

                JSONObject data = response.getJSONObject("data");
                String userId = data.getString("userId");
                String userName = data.getString("userName");
                String token = data.getString("tokenMsg");
                String userMobile = data.getString("userMobile");
                String employeeNo = data.getString("workNumber");
                Long lEntryTime = (Long) data.get("inputTime");

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                String entryTime = simpleDateFormat.format(new Date(lEntryTime));
                String email = data.getString("userEmail");
                String positionName = data.getString("positionName");
                String depNames = "";
                JSONArray depList = data.getJSONArray("oaDepartmentList");
                for (int index = 0; index < depList.length(); index++) {
                    JSONObject jsonItem = depList.getJSONObject(index);
                    if (index == depList.length() - 1)
                        depNames += jsonItem.getString("depNmae");
                    else
                        depNames += jsonItem.getString("depNmae") + " | ";
                }

                LoggedInUser users = new LoggedInUser();
                users.setUserId(userId);
                users.setToken(token);
                users.setUserName(userName);
                users.setMobile(userMobile);
                users.setEmail(email);
                users.setEmployeeNo(employeeNo);
                users.setPositionName(positionName);
                users.setEntryTime(entryTime);
                users.setDepName(depNames);

                App.setLoggedInUser(users);

                Message message = new Message();
                //区分标志
                message.what = 200;
                //传参到ui线程
                message.obj = users;
                handler.sendMessage(message);
                return;
            }

            loginExceptionHandler(response.getString("message"));
            Log.d("响应结果", response.toString());

        } catch (InterruptedException e) {
            // exception handling
            e.printStackTrace();

            loginExceptionHandler(e.getMessage());

        } catch (ExecutionException e) {
            // exception handling
            e.printStackTrace();

            loginExceptionHandler(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();

            loginExceptionHandler(e.getMessage());
        }
//                catch (TimeoutException e) {
//                    e.printStackTrace();
//                }

    }

    private void loginExceptionHandler(String message2) {
        Message message = new Message();
        //区分标志
        message.what = -1;
        message.obj = message2;
        //传参到ui线程
        handler.sendMessage(message);
    }

    //文本框监听事件
    public void loginDataChanged(String username, String password) {
        if (!isUserNameValid(username)) {
            loginFormState.setValue(new LoginFormState(R.string.invalid_username, null));
        } else if (!isPasswordValid(password)) {
            loginFormState.setValue(new LoginFormState(null, R.string.invalid_password));
        } else {
            loginFormState.setValue(new LoginFormState(true));
        }
    }

    // A placeholder username validation check
    private boolean isUserNameValid(String username) {
        if (username == null) {
            return false;
        }
        if (username.contains("@")) {
            return Patterns.EMAIL_ADDRESS.matcher(username).matches();
        } else {
            return !username.trim().isEmpty();
        }
    }

    // A placeholder password validation check
    private boolean isPasswordValid(String password) {
        return password != null && password.trim().length() > 5;
    }
}